/**
 * Copyright (c) 2015-2017, Javen Zhou  (javen205@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.javen.weixin.controller;

import java.util.List;

import com.javen.weixin.Interceptor.ConfigInterceptor;
import com.javen.weixin.common.model.Config;
import com.javen.weixin.common.model.Custommenu;
import com.javen.weixin.common.model.Matchrulemenu;
import com.javen.weixin.common.model.Menutype;
import com.javen.weixin.menu.Button;
import com.javen.weixin.menu.ClickButton;
import com.javen.weixin.menu.ComButton;
import com.javen.weixin.menu.Matchrule;
import com.javen.weixin.menu.MediaButton;
import com.javen.weixin.menu.Menu;
import com.javen.weixin.menu.MiniProgramButton;
import com.javen.weixin.menu.ViewButton;
import com.javen.weixin.service.CustomMenuService;
import com.javen.weixin.service.MatchruleMenuService;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;

/**
 * @author Javen
 * 2017年6月18日
 */
@Before(ConfigInterceptor.class)
public class CustomMenuController extends Controller {
	Log log = Log.getLog(CustomMenuController.class);
	
	static CustomMenuService cms = CustomMenuService.me;
	static Menutype menuTypeDao = new Menutype().dao();
	static MatchruleMenuService mms= MatchruleMenuService.me;
	
	public void create(){
		Config config = (Config) getSession().getAttribute("config");
		
		String jsonMenu = JsonKit.toJson(getCreateMenu(config.getAppId(),null)).toString();
		log.info(jsonMenu);
		//创建菜单
        ApiResult apiResult=MenuApi.createMenu(jsonMenu);
        log.info(apiResult.getJson());
        renderText(jsonMenu);
		
	}
	
	public void addConditional(){
		Config config = (Config) getSession().getAttribute("config");
		String appId = config.getAppId();
		//通过APPId查询个性菜单
		List<Matchrulemenu> matchruleMenus = mms.getMatchruleMenuByAppId(appId);
		for (Matchrulemenu matchrulemenu : matchruleMenus) {
			String jsonMenu = JsonKit.toJson(getCreateMenu(appId,matchrulemenu)).toString();
			log.info("生成菜单的json:"+jsonMenu);
			//创建菜单
	        ApiResult apiResult=MenuApi.addConditional(jsonMenu);
	        log.info("接口返回的json:"+apiResult.getJson());
		}
		
        renderText("OK...");
	}
	/**
	 * 根据appId创建自定义菜单
	 * @param appId
	 * @param isConditiona 是否是个性化菜单
	 * @return
	 */
	private Menu getCreateMenu(String appId,Matchrulemenu matchrulemenu){
		int menu_guoup = 0;
		if (null!=matchrulemenu) {
			menu_guoup = matchrulemenu.getMenuGroup();
		}
		List<Custommenu> mainMenu = cms.getMenueByAppId(appId,0,menu_guoup);
		if (null != mainMenu && mainMenu.size()>0) {
			//初始化主菜单的个数
			Button[] buttons = new Button[mainMenu.size()];
			//遍历主菜单
			for (int i = 0; i < mainMenu.size(); i++) {
				Integer mainTypeId = mainMenu.get(i).getTypeId();
				if (mainTypeId != 11) {					
					//无个子菜单
					Custommenu custommenu = mainMenu.get(i);
					String key = custommenu.getKey();
					String name = custommenu.getName();
					String url = custommenu.getUrl();
					String mediaId = custommenu.getMediaId();
					String xappid = custommenu.getXappid();
					String pagepath = custommenu.getPagepath();
					Button mainButton = getButton(mainTypeId, key, name, url, mediaId, xappid, pagepath);
					buttons[i] = mainButton;
				}else {
					//有子菜单
					ComButton main = new ComButton();
					main.setName(mainMenu.get(i).getName());
					//添加子菜单
					
					List<Custommenu> subMenu = cms.getMenueByAppId(appId, mainMenu.get(i).getId(),menu_guoup);
					if (null != subMenu && subMenu.size()>0) {
						Button[] subButtons = new Button[subMenu.size()];
						for (int j = 0; j < subMenu.size(); j++) {
							Integer subTypeId = subMenu.get(j).getTypeId();
							String subName = subMenu.get(j).getName();
							String subKey = subMenu.get(j).getKey();
							String subUrl = subMenu.get(j).getUrl();
							String mediaId = subMenu.get(j).getMediaId();
							String xappid = subMenu.get(j).getXappid();
							String pagepath = subMenu.get(j).getPagepath();
							Button subButton = getButton(subTypeId, subKey, subName, subUrl, mediaId , xappid, pagepath);
							subButtons[j] = subButton;
						}
						main.setSub_button(subButtons);
						buttons[i] = main;
					}
				}
			}
			Menu menu = new Menu();  
			menu.setButton(buttons); 
			//个性化菜单条件
			if (null!=matchrulemenu) {
				Matchrule matchrule = new Matchrule(matchrulemenu);
				menu.setMatchrule(matchrule);
			}
			return menu;  
		}
        return null;  
	}
	
	/**
	 * 根据菜单类型获取Button
	 * @param typeId
	 * @param key
	 * @param name
	 * @param url
	 * @param mediaId
	 * @param pagepath 
	 * @return
	 */
	private Button getButton(int typeId,String key,String name,String url,String mediaId,String xappid, String pagepath){
		Menutype menutype = menuTypeDao.findById(typeId);
		if (null != menutype) {
			String typeName = menutype.getTypeName();
			
			if (typeName.equals("click") 
					|| typeName.equals("scancode_push") 
					|| typeName.equals("scancode_waitmsg") 
					|| typeName.equals("pic_sysphoto")
					|| typeName.equals("pic_photo_or_album")
					|| typeName.equals("pic_weixin")
					|| typeName.equals("location_select")) {
				ClickButton button = new ClickButton();
				button.setKey(key);
				button.setName(name);
				button.setType(typeName);
				return button;
			}else if (typeName.equals("view")) {
				ViewButton button = new ViewButton();
				button.setUrl(url);
				button.setName(name);
				button.setType(typeName);
				return button;
			}else if (typeName.equals("media_id") 
					|| typeName.equals("view_limited")) {
				MediaButton button = new MediaButton();  
				button.setName(name);  
				button.setType(typeName);  
				button.setMedia_id(mediaId);
				return button;
			}else if (typeName.equals("miniprogram")) {
				MiniProgramButton button = new MiniProgramButton();  
				button.setName(name);  
				button.setType(typeName);  
				button.setAppid(xappid);
				button.setPagepath(pagepath);
				return button;
			}
		}
		
		return null;
	}
}
